#!/bin/bash
############################################################################
# Copyright (C) 2007 Lawrence Livermore National Security, LLC
# Produced at Lawrence Livermore National Laboratory.
# Written by Jim Garlick <garlick@llnl.gov>.
# UCRL-CODE-235119
# 
# This file is part of nfsroot, a network root file system utility.
# 
# nfsroot is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# nfsroot is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with nfsroot; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
############################################################################
#
# rc.nfsroot-bind - nfsroot startup (bind method)
#
# Root is a shared ro nfs file system with configured directories copied into
# /writeable (ramdisk) and bind mounted back on top if the source directory.
#
export PATH=/bin:/sbin:/usr/bin:/usr/sbin
RAMDIRS="/etc /var"
PREINITPROG=/etc/rc.nfsroot-init
configfile=/etc/sysconfig/nfsroot
if [ -f $configfile ]; then
   . $configfile
fi
prog=rc.nfsroot-bind

if touch / 2>/dev/null; then
   echo "${prog}: root file system is read-write" >&2
   return 1 
fi

mnt_options="mode=755,nr_inodes=0${TMPFSMAX:+,size=${TMPFSMAX}}"
echo "${prog}: mounting ramdisk with ${mnt_options}"
if ! mount -n -t tmpfs -o${mnt_options} none /writeable; then
    echo "${prog}: mount failed"
    return 1
fi

set -o noglob

for dir in ${RAMDIRS}; do
    [ -e ${dir} ] || panic "${prog}: ${dir} does not exist"
    [ -d ${dir} ] || panic "${prog}: ${dir} is not a directory"

    rsync_exclude=""
    for nocopy_dir in ${RAMDIRS_NOCOPY} ; do
        suffix=${nocopy_dir#${dir}/}
        [ "$suffix" = "$nocopy_dir" ] \
            || rsync_exclude="${rsync_exclude} --exclude /${suffix}/**"
    done

    echo "${prog}: copying $dir to ramdisk"
    mkdir -p /writeable${dir}
    if ! rsync -aH ${rsync_exclude} ${dir}/ /writeable${dir} 2>/dev/null; then
        echo "${prog}: copy failed"
        umount /writeable
        return 1
    fi
done
for dir in ${RAMDIRS}; do
    mount -n --bind /writeable${dir} ${dir}
done

echo "${prog}: passing control to ${PREINITPROG}" >&2
exec ${PREINITPROG} "$@" </dev/console >/dev/console 2>&1
return 1
